package com.uduemc.biso.master.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.MasterUser;
import com.uduemc.biso.core.utils.JsonResult;
import com.uduemc.biso.master.backend.components.LoginForm;
import com.uduemc.biso.master.backend.service.MastermanageService;

@Controller
public class IndexController {

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Autowired
	private MastermanageService mastermanageServiceImpl;

	@GetMapping(value = { "/", "/login.html", "/index.html" })
	public String login(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.removeAttribute("loginForm");
		return "index";
	}

	@PostMapping(value = { "/login" })
	@ResponseBody
	public JsonResult loginPost(@RequestParam("username") String username, @RequestParam("password") String password,
			HttpServletRequest request)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
			return JsonResult.illegal();
		}
		MasterUser masterUser = mastermanageServiceImpl.getByUsername(username);
		if (masterUser == null) {
			return JsonResult.messageError("账号或密码错误！");
		}
		boolean matches = passwordEncoder.matches(password, masterUser.getPasswordHash());
		if (!matches) {
			return JsonResult.messageError("账号或密码错误！");
		}
		LoginForm loginForm = new LoginForm();
		loginForm.setMasterUser(masterUser);
		HttpSession session = request.getSession();
		session.setAttribute("loginForm", loginForm);
		return JsonResult.ok("/backend/index.html");
	}
}
